package cn.dglydrpy.study.ssm.common.kafka.serializer;

import java.nio.ByteBuffer;
import java.util.Map;

import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Serializer;

import cn.dglydrpy.study.ssm.common.kafka.domain.Customer;
/**
 * 序列化
	1) 创建模型
	2) 创建自定义的序列化器
	3) 替换值的序列化器
	4) 更改生产者
	5) 更改消息类型
 * @author hasee
 *
 */
public class CustomerSerializer implements Serializer<Customer> {
    @Override
    public void configure(Map<String, ?> map, boolean b) {

    }

    @Override
    public byte[] serialize(String s, Customer customer) {
        try {
            byte[] serializedName;
            int stringSize;
            if( null == customer) {
                return null;
            }
            if(null != customer.getCustomerName()){
                serializedName = customer.getCustomerName().getBytes("UTF-8");
                stringSize = serializedName.length;
            } else {
                serializedName = new byte[0];
                stringSize = 0;
            }
            ByteBuffer buffer = ByteBuffer.allocate(4+4+stringSize);
            buffer.putInt(customer.getId());
            buffer.putInt(stringSize);
            buffer.put(serializedName);
            return buffer.array();
        } catch (Exception e){
            e.printStackTrace();
            throw new SerializationException("在序列化Customer的时候出现异常"+e);
        }
    }

    @Override
    public void close() {

    }
}
